package cn.kgc.controller;

import cn.kgc.pojo.Role;
import cn.kgc.pojo.User;
import cn.kgc.service.UserService;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.naming.NoPermissionException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author 蒿雨
 * @create 2021-11-02 19:52
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    //修改方法
    @RequestMapping("/modifyUser")
    public String modifyUser(@ModelAttribute User user, HttpSession session) {
        User user1 = (User) session.getAttribute("loginUser");
        user.setModifyBy(user1.getId());
        user.setModifyDate(new Date());
        if (userService.userModify(user)) {
            System.out.println("修改成功！");
            return "redirect:/user/userlist";
        }
        return "usermodify";

    }

    //修改赋值
    @RequestMapping("/toModify/{id}")
    public String toModify(@PathVariable int id, HttpSession session) {
        session.setAttribute("user", userService.getUserById(id));
        return "usermodify";
    }

    //查看方法
    @RequestMapping("/view/{id}")
    public String userVier(@PathVariable int id, HttpSession session) {
        session.setAttribute("user", userService.getUserById(id));
        return "userview";
    }


    @RequestMapping("/userDel")
    @ResponseBody
    public String userDel(int uid) {
        Map<String, Object> map = new HashMap<>();
        if (userService.isNull(uid)) {
            map.put("delResult", "notexist");
            return JSON.toJSONString(map);
        }
        if (userService.userDel(uid) > 0) {
            map.put("delResult", true);
            return JSON.toJSONString(map);
        }
        map.put("delResult", false);
        return JSON.toJSONString(map);

    }


    //添加方法
    @RequestMapping("/useraddsave")
    public String useraddsave(@RequestParam(value = "attchs", required = false) MultipartFile multipartFile, User user, HttpSession session, HttpServletRequest request) {
        //上升作用域
        String idPicPathError = "";
        String newFileName = "";
        String fileUploadPath = "";
        //判断是否上传了文件
        if (multipartFile != null) {
            //1.进行准备工作
            //获取文件夹的绝对路径
            fileUploadPath = session.getServletContext().getRealPath("statics" + File.separator + "uploadFiles");
            System.out.println(fileUploadPath);
            //获取文件名
            String fileName = multipartFile.getOriginalFilename();
            //判断文件大小
            if (multipartFile.getSize() > 5000000) {
                idPicPathError = "上传的文件超过限制大小";
                request.setAttribute("idPicPathError", idPicPathError);
                return "useradd";
            }
            //前后缀
            String prefix = fileName.substring(0, fileName.indexOf("."));
            String suffix = fileName.substring(fileName.indexOf(".") + 1);

            //判断文件类型
            List<String> list = new ArrayList<>();
            list.add("jpg");
            list.add("jpeg");
            list.add("png");
            if (!list.contains(suffix)) {
                idPicPathError = "上传文件不符合格式!";
                request.setAttribute("idPicPathError", idPicPathError);
                return "useradd";
            }
            //定义上传的文件名
            newFileName = prefix + (int) (Math.random() * (100000 - 10000) + 10000) + "" + System.currentTimeMillis()+"."+ suffix;
            //创建文件上传容器(上传的绝对路径,文件名)
            File file = new File(fileUploadPath, newFileName);
            if (!file.exists()) {
                file.mkdirs();//创建文件夹
            }
            try {
                multipartFile.transferTo(file);
            } catch (IOException e) {
                e.printStackTrace();
                request.setAttribute("idPicPathError", "系统错误!请重试!");
                return "useradd";
            }
        }
        User user1 = (User) session.getAttribute("loginUser");
        user.setCreatedBy(user1.getId());
        user.setCreationDate(new Date());
        //添加文件路径
        user.setIdPicPath(fileUploadPath + newFileName);

        int a = userService.addUser(user);
        if (a > 0) {
            System.out.println("添加成功！");
            return "redirect:/user/userlist";
        }
        System.out.println("添加失败");
        return "/touseradd";
    }


    //判断重复方法
    @RequestMapping("/userCodeIsExists/{userCode}")
    @ResponseBody
    public String userCodeIsExists(@PathVariable String userCode) {
        Map<String, Object> map = new HashMap<>();
        User user = userService.getUserForUserCode(userCode);
        System.out.println(userCode);
        if (user == null) {
            map.put("userCode", "noexist");
        } else {
            map.put("userCode", "exist");
        }
        return JSON.toJSONString(map);
    }

    //添加角色表
    @RequestMapping("/getRoleList")
    @ResponseBody
    public String getRoleList() {
        List<Role> roles = userService.ROLES();
        return JSON.toJSONString(roles);
    }

    //跳转到添加页面
    @RequestMapping("/touseradd")
    public String touseradd() {
        return "useradd";
    }


    @RequestMapping("/dologin")
    public String dologin(String userCode, String userPassword, HttpSession session, HttpServletRequest request) {
        User user = userService.getLogin(userCode, userPassword);
        if (user == null) {
            System.out.println("登录失败，账号或密码错误");
            request.getSession().setAttribute("error", "登录失败，账号或密码错误");
            return "login";
        }
        session.setAttribute("loginUser", user);
        return "frame";
    }

    //注销方法
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("loginUser");
        return "login";
    }

    //权限拦截
    @RequestMapping("/login")
    public String login(HttpSession session) throws NoPermissionException {
        User user = (User) session.getAttribute("loginUser");
        if (user == null) {
            throw new NoPermissionException("抱歉，找不到页面");
        }
        return "frame";
    }

    @RequestMapping("/userlist")
    public String userList(HttpSession session, HttpServletRequest request, String pageIndex, String queryname, String queryUserRole) {
        int pageSize = 5;
        int index = 1;
        if (pageIndex != null) {
            index = Integer.parseInt(pageIndex);
        }
        Map<String, Object> map = new HashMap<>();
        System.out.println(queryname);
        System.out.println(queryUserRole);
        map.put("index", index);
        map.put("pageSize", pageSize);
        map.put("queryname", queryname);
        map.put("queryUserRole", queryUserRole);
        session.setAttribute("roleList", userService.ROLES());
        session.setAttribute("page", userService.getUsers(map));
        //数据回显
        request.setAttribute("queryUserName", queryname);
        request.setAttribute("queryUserRole", queryUserRole);
        return "userlist";
    }


}
